import { ElMessage } from 'element-plus'

export const config = {
  baseRoot: '', // 静态资源前缀
  baseUrl: '', // 接口前缀
  token: ''
}

export default async function request({ url, method, header, data }) {
  const options = {
    method: method.toUpperCase() ?? 'GET',
    headers: {},
    mode: 'cors',
    credentials: 'same-origin'
  }
  const re = /^http/

  if (header) {
    options.headers = header
  } else {
    if (data instanceof FormData) {
      options.body = data
    } else {
      options.headers = {
        'Content-Type': 'application/json'
        // 'Content-Type': 'application/x-www-form-urlencoded',
      }
      options.body = JSON.stringify(data)
    }
  }

  options.headers['Authorization'] = `Bearer ${config.token}`

  function checkError(code, message) {
    return console.error(message)
  }

  let response
  try {
    response = await fetch(re.test(url) ? url : config.baseUrl + url, options)
  } catch (error) {
    checkError(0, error.message)

    return error
  }

  const contentType = response.headers.get('Content-Type')

  if (response.ok) {
    if (contentType?.includes('application/json')) {
      const res = await response.json()
      return res
    } else if (contentType?.includes('text/html')) return response.text()
    else return response.blob()
  } else {
    if (contentType?.includes('application/json')) {
      const res = await response.json()
      checkError(res.code, res.message)
      return res
    }

    checkError(response.status, response.statusText)
    return response
  }
}
// 静态资源路径处理
export function staticUrl(path) {
  return path?.startsWith('/') ? config.baseRoot + path : path
}
